package org.uim.cricket.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBThread {

	private static String dbClass = "com.mysql.jdbc.Driver";
	private static String dbConnectionStr = "jdbc:mysql://localhost/mycricket";
	private static String dbUser = "root";
	private static String dbPassword = "chaturika";
	
	private String query = null;
	private ResultSet resultSet = null;
	private Connection con = null;
	private Statement statement = null;
	
	static {
		try {
			Class.forName(dbClass);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public static void setDatabaseConnectionIdentifier(DBSchemaIdentifiable dbid) {
		dbClass = dbid.getDatabaseDriver();
		dbConnectionStr = dbid.getDatabaseConnectionStr();
		dbUser = dbid.getDatabaseUserName();
		dbPassword = dbid.getDatabasePassword();
	}
	
	public DBThread(String query) {
		this.query = query;
	}

	private void initDB() throws SQLException {
		con = DriverManager.getConnection(dbConnectionStr, dbUser, dbPassword);
	} 
	
	public void close() throws SQLException {
		try {
			if (this.resultSet != null  && !this.resultSet.isClosed()) resultSet.close();
			statement.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
	}
	
	public void run() throws SQLException {
		
		try {
			
			this.initDB();
			
			statement = con.createStatement();
			
			this.resultSet = statement.executeQuery(this.query);
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		
	}
	
	public void setQuery(String query) {
		this.query = query;
	}
	
	public String getQuery() {
		return query;
	}
	
	public ResultSet getResultSet() {
		return resultSet;
	}
	
	public Statement getStatement() {
		return statement;
	}
	
	
}
